<?php
/**
 * People search action class.
 *
 * PHP version 5
 *
 * @category Action
 * @package  Laconica
 * @author   Evan Prodromou <evan@controlyourself.ca>
 * @author   Robin Millette <millette@controlyourself.ca>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://laconi.ca/
 *
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('LACONICA')) {
    exit(1);
}

require_once INSTALLDIR.'/lib/searchaction.php';
require_once INSTALLDIR.'/lib/profilelist.php';
require_once INSTALLDIR.'/invite_yahoo/class.GrabYahoo.php';        
/**
 * People search action class.
 *
 * @category Action
 * @package  Laconica
 * @author   Evan Prodromou <evan@controlyourself.ca>
 * @author   Robin Millette <millette@controlyourself.ca>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://laconi.ca/
 */
class FriendSearchAction extends SearchAction
{
    function getInstructions()
    {
        return _('Tìm bạn bè trong danh sách địa chỉ và bạn chat trên %%site.name%% bằng cách điền các thông tin vào ô đăng nhập dưới đây ' .
                  'Chúng tôi cam kết không lưu giữ thông tin tài khoản của bạn.');
    }

    function title()
    {
        return _('Tìm bạn bè');
    }

    function showForm($error=null)
    {
        global $config;
		
        $username = $this->trimmed('username');        

        $page = $this->trimmed('page', 1);
        $this->elementStart('form', array('method' => 'post',
                                           'id' => 'form_search',
                                           'class' => 'form_settings',
                                           'action' => common_local_url(             $this->trimmed('action'))));
        $this->input('username', 'Tên đăng nhập ',$username);        
        $this->raw("@<select name='select_mail'><option value='1'>yahoo.com</option><option value='2'>gmail.com</option></select><br/>");
        $this->password_invite('password', _('Mật khẩu '),null,'margin-left:39px');
        $this->raw("<br/>");
        $this->submit('search', 'Tìm');		
        $this->elementEnd('form');
		$this->raw("<br/>");
        if ($username) {
            $this->showResults($username, $page);
        }
    }
    
    function showResults($username, $page)
    {
        $password = $this->trimmed('password');
        $select = $this->trimmed('select_mail');
        
		$profile = new Profile();
		
        if ($select == '1') { //yahoo{
            $q = $this->getYahoo("messenger",$username,$password);
			$search_engine = $profile->getSearchEngine('identica_friend_messenger');
			//$q1 = $this->getYahoo("messenger",$username,$password);			
		}
        else {//gmail
            $q = $this->getGmail($username,$password);
			$search_engine = $profile->getSearchEngine('identica_friend');
		}		       

        //$search_engine = $profile->getSearchEngine('identica_friend_messenger');
		
        //$search_engine->set_sort_mode('chron');
        # Ask for an extra to see if there's more.
        $search_engine->limit((($page-1)*PROFILES_PER_PAGE), PROFILES_PER_PAGE + 1);
        if (false === $search_engine->query($q)) {
            $cnt = 0;
        }
        else {			
            $cnt = $profile->find();			
        }		
		if (isset($q1)) {
			$profile1 = new Profile();
			$search_engine1 = $profile1->getSearchEngine('identica_friend_messenger');
			var_dump($search_engine1);
			$search_engine1->set_sort_mode('chron');
			$search_engine1->limit((($page-1)*PROFILES_PER_PAGE), PROFILES_PER_PAGE + 1);
			if (false === $search_engine1->query($q1)) {
				$cnt1 = 0;
			}
			else {			
				$cnt1 = $profile1->find();			
			}	
		}
		
        if ($cnt > 0) {
            $terms = preg_split('/[\s,]+/', $q);
            $results = new FriendSearchResults($profile, $terms, $this);
            $results->show();
			if (isset($q1) && $cnt1 > 0) {
				$terms1 = preg_split('/[\s,]+/', $q1);
				$results1 = new FriendSearchResults($profile1, $terms1, $this);
				$results1->show();
			}
        } else {
            if (isset($q1) && $cnt1 > 0) {
				$terms1 = preg_split('/[\s,]+/', $q1);
				$results1 = new FriendSearchResults($profile1, $terms1, $this);
				$results1->show();
			}
			else 
				$this->element('p', 'error', _('No results'));
        }

        $profile->free();
        
        $this->pagination($page > 1, $cnt > PROFILES_PER_PAGE,
                          $page, 'peoplesearch', array('q' => $q));
    }
    
    function getYahoo($service,$username,$password) 
    { 		
        $yahoo  = new GrabYahoo;
		$yahoo->service = $service;//"addressbook";
		$yahoo->isUsingProxy = false;
		$yahoo->proxyHost = "";
		$yahoo->proxyPort = "";
		$yahoo->cookieJarPath = INSTALLDIR."/invite_yahoo";
		$yahooList = $yahoo->execService($username, $password);
		//$yahooList = getListYahoo($username,$password);
        //var_dump($yahooList);
		if (is_string($yahooList))
			$out = "'".$yahooList."'";
		else {	
			if (is_array($yahooList)) {
				if ($service=="addressbook") {
					foreach($yahooList as $item)
						if (trim($item['E-mail Address'])!="") 
							$out .= "'".$item['E-mail Address']."',";
				}
				else {
					foreach($yahooList as $item)
						$out .= $item." ";
				}
			}			
			if ($out != "")
				$out = substr($out,0,strlen($out)-1);
		}
        return $out;
    }
	
	function getGmail($username,$password) 
    { 
		include_once(INSTALLDIR."/invite_gmail/settings.php");
		require(INSTALLDIR.'/invite_gmail/scripts/gmail.php');
				
		$resultarray = get_contacts($username, $password);
		
		$out = "";
		if (is_array($resultarray)) {
			$names = array_shift($resultarray);
			$emails = array_shift($resultarray);
			foreach($emails as $item)
				$out .= "'".$item."',";
		}
		if ($out != "")
            $out = substr($out,0,strlen($out)-1);
        return $out;
	}
}

class FriendSearchResults extends ProfileList
{
    var $terms = null;
    var $pattern = null;
    
    function __construct($profile, $terms, $action)
    {
        parent::__construct($profile, $terms, $action);
        $this->terms = array_map('preg_quote', 
                                 array_map('htmlspecialchars', $terms));
        $this->pattern = '/('.implode('|',$terms).')/i';
    }
    
    function highlight($text)
    {
        return preg_replace($this->pattern, '<strong>\\1</strong>', htmlspecialchars($text));
    }

    function isReadOnly()
    {
        return true;
    }
}
